package com.uduew.sjd.ui.bind

import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.graphics.Outline
import android.graphics.drawable.Drawable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import android.view.ViewOutlineProvider
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.text.HtmlCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.get
import androidx.core.view.isNotEmpty
import androidx.core.view.updateLayoutParams
import androidx.core.widget.NestedScrollView
import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.drake.statelayout.StateLayout
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.button.MaterialButton
import com.google.android.material.navigation.NavigationBarView
import com.google.android.material.tabs.TabLayout
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.CameraView
import com.raedev.forms.FormGroupAdapter
import com.raedev.forms.view.FormLayoutManager
import com.smallmarker.tagflowlayout.TagFlowAdapter
import com.smallmarker.tagflowlayout.TagFlowLayout
import com.uduew.sjd.R
import com.uduew.sjd.api.HandlingChargeApi
import com.uduew.sjd.api.ProductInfoApi
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.config.Const
import com.uduew.sjd.ui.MainFragment
import com.uduew.sjd.ui.login.LoginActivity
import com.uduew.sjd.utils.DensityUtil
import com.uduew.sjd.utils.MainHandler
import com.uduew.sjd.utils.ResUtil
import com.uduew.sjd.utils.SpannableUtils
import com.uduew.sjd.utils.Utils
import com.uduew.sjd.view.CodeInputView
import com.uduew.sjd.view.CountDownTextView
import com.uduew.sjd.view.EmptyView
import com.uduew.sjd.view.FullyGridLayoutManager
import com.uduew.sjd.view.GridSpacingItemDecoration
import com.uduew.sjd.view.PercentageSeekBar
import com.uduew.sjd.view.xpop.DetailsXpop
import java.io.File

object CommonBindingAdapter {


    @JvmStatic
    @BindingAdapter(value = ["bottomInset"], requireAll = false)
    fun bottomInset(view: View, open: Boolean) {
        var isApplyingInsets = false
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            if (isApplyingInsets) return@setOnApplyWindowInsetsListener insets
            isApplyingInsets = true
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.updateLayoutParams<MarginLayoutParams> {
                bottomMargin = systemBars.bottom
            }
            insets
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["isSelected"], requireAll = false)
    fun setIsSelected(textView: AppCompatTextView, isSelected: Boolean) {
        textView.isSelected = isSelected
    }



    @JvmStatic
    @BindingAdapter(value = ["textUnderLine"], requireAll = false)
    fun setTextUnderLine(textView: AppCompatTextView, text: String?) {
        if (text != null) {
            val content = SpannableString(text)
            content.setSpan(UnderlineSpan(), 0, content.length, 0)
            textView.setText(content)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["shamosState"], requireAll = false)
    fun shamosState(view: AppCompatTextView, state: Boolean) {
        if (state) {
            view.visibility = View.VISIBLE
        } else {
            view.visibility = View.GONE
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["orderState"], requireAll = false)
    fun orderState(view: View, state: String) {
        if (view.id == R.id.cl_details_repayment) {
            if (state == "firemen" || state == "breeks") {
                view.visibility = View.VISIBLE
            } else {
                view.visibility = View.GONE
            }
        }
        if (view.id == R.id.tv_contact_customer_service) {
            if (state == "culminate" || state == "pathetical" || state == "firemen" || state == "breeks" || state == "monica" || state == "missive") {
                view.visibility = View.VISIBLE
            } else {
                view.visibility = View.GONE
            }
            if (view is MaterialButton) {
                if (state == "firemen" || state == "monica" || state == "breeks") {
                    view.text = "Trả nợ ngay lập tức"
                } else if (state == "missive") {
                    view.text = "Mượn thêm một cái nữa"
                } else {
                    view.text = "Liên hệ dịch vụ khách hàng"
                }
            }
        }
        if (view.id == R.id.tv_extended_repayment) {
            if (state == "firemen" || state == "breeks") {
                view.visibility = View.VISIBLE
            } else {
                view.visibility = View.GONE
            }
        }

    }


    @JvmStatic
    @BindingAdapter(value = ["loanStateTip"], requireAll = false)
    fun loanStateTip(view: AppCompatTextView, state: String) {
        if (state == "underwent") {
            view.text = ResUtil.getString(R.string.underwent_str)
        } else if (state == "culminate" || state == "pathetical") {
            view.text = ResUtil.getString(R.string.culminate_str)
        } else if (state == "firemen") {
            view.text = ResUtil.getString(R.string.firemen_str)
        } else if (state == "breeks") {
            view.text = ResUtil.getString(R.string.breeks_str)
        } else if (state == "missive") {
            view.text = ResUtil.getString(R.string.missive_str)
        }
    }

    private const val UNDERWENT = "underwent"
    private const val MONICA = "monica"
    private const val CULMINATE = "culminate"
    private const val FIREMEN = "firemen"
    private const val PATHETICAL = "pathetical"
    private const val BREKS = "breeks"
    private const val MISSIVE = "missive"

    private fun applyCommonStyle(view: TextView, bgRes: Int, colorRes: Int) {
        if (bgRes != -1) {
            view.setBackgroundResource(bgRes)
        }
        view.setTextColor(ContextCompat.getColor(view.context, colorRes))
    }

    private fun handleLoanStateCommon(view: AppCompatTextView, state: String) {
        val (textRes, bgRes, colorRes) = when (state) {
            UNDERWENT -> Triple(
                R.string.audit_in_progress,
                R.drawable.rounded_4dp_blue_background,
                R.color.blue_1100
            )

            MONICA -> Triple(
                R.string.approved,
                R.drawable.rounded_4dp_blue_background,
                R.color.blue_1100
            )

            CULMINATE -> Triple(
                R.string.rejected,
                R.drawable.rounded_4dp_red_background,
                R.color.red_20
            )

            FIREMEN -> Triple(
                R.string.pending_repayment,
                R.drawable.rounded_4dp_blue_background,
                R.color.blue_1100
            )

            PATHETICAL -> Triple(
                R.string.loan_failed,
                R.drawable.rounded_4dp_red_background,
                R.color.red_20
            )

            BREKS -> Triple(R.string.overdue, R.drawable.rounded_4dp_red_background, R.color.red_20)
            MISSIVE -> Triple(
                R.string.settled,
                R.drawable.rounded_4dp_grey_background,
                R.color.grey_160
            )

            else -> return.also { view.visibility = View.GONE }
        }

        view.apply {
            visibility = View.VISIBLE
            text = context.getString(textRes)
            if (view.id == R.id.tv_order_value) {
                if (state == FIREMEN) {
                    text = context.getString(R.string.in_payment)
                }
                applyCommonStyle(this, -1, colorRes)
            } else {
                applyCommonStyle(this, bgRes, colorRes)
            }
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["repaymentState"], requireAll = false)
    fun repaymentState(view: AppCompatTextView, state: String?) {
        state ?: return
        when (view.id) {
            R.id.tv_roll_over_repayment, R.id.tv_goto_repayment -> {
                view.visibility =
                    if (state == FIREMEN || state == BREKS) View.VISIBLE else View.GONE
            }

            R.id.tv_order_value -> handleLoanStateCommon(view, state)
            R.id.tv_loan_state -> handleLoanStateCommon(view, state)
            R.id.tv_lan_state_title -> {
                view.text = when (state) {
                    UNDERWENT -> ResUtil.getString(R.string.loan_audit_in_progress)
                    CULMINATE -> ResUtil.getString(R.string.audit_failed)
                    else -> return.also { view.visibility = View.GONE }
                }
                view.visibility = View.VISIBLE
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["loanState"], requireAll = false)
    fun loanState(view: View, state: String?) {
        state ?: return
        when (view.id) {
            R.id.tv_loan_state -> (view as? AppCompatTextView)?.let {
                handleLoanStateCommon(
                    it,
                    state
                )
            }

            R.id.tv_lan_state_title -> (view as? AppCompatTextView)?.apply {
                text = when (state) {
                    UNDERWENT -> context.getString(R.string.loan_audit_in_progress)
                    CULMINATE -> context.getString(R.string.audit_failed)
                    PATHETICAL -> context.getString(R.string.loan_failed)
                    FIREMEN -> context.getString(R.string.pending_repayment)
                    MONICA -> context.getString(R.string.approved)
                    BREKS -> context.getString(R.string.overdue)
                    MISSIVE -> context.getString(R.string.settled)
                    else -> return@apply.also { visibility = View.GONE }
                }
                visibility = View.VISIBLE
            }

            R.id.iv_loan_state -> (view as? AppCompatImageView)?.apply {
                val iconRes = when (state) {
                    UNDERWENT -> R.mipmap.loan_review_ing_icon
                    CULMINATE, PATHETICAL -> R.mipmap.loan_review_faild_icon
                    MONICA, FIREMEN -> R.mipmap.loan_wait_repayment_icon
                    BREKS -> R.mipmap.loan_overdue_ed_icon
                    MISSIVE -> R.mipmap.loan_settle_ed_icon
                    else -> return@apply.also { visibility = View.GONE }
                }
                setImageResource(iconRes)
                visibility = View.VISIBLE
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["bindTabLayoutListener"], requireAll = false)
    fun listenTabLayout(tabLayout: TabLayout, listener: TabLayout.OnTabSelectedListener) {
        tabLayout.addOnTabSelectedListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["defSelect"], requireAll = false)
    fun defSelect(tabLayout: TabLayout, select: Int) {
        tabLayout.selectTab(tabLayout.getTabAt(select))
    }


    @JvmStatic
    @BindingAdapter(value = ["bindTabMenu"], requireAll = false)
    fun initTabMenu(navigationView: BottomNavigationView, type: String) {


    }

    @JvmStatic
    @BindingAdapter(value = ["imageNum"], requireAll = false)
    fun imageNum(textView: AppCompatTextView, num: Int) {
        textView.text = num.toString() + "/5"
    }

    @JvmStatic
    @BindingAdapter(value = ["loginState"], requireAll = false)
    fun loginState(view: View, isLogin: Boolean) {
        if (view.id == R.id.toLogin_tv || view.id == R.id.usernick_tv) {
            view.visibility = if (isLogin) View.GONE else View.VISIBLE
        }

        if (view.id == R.id.userPhone_tv) {
//            view.
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["selectPage"], requireAll = false)
    fun selectPage(viewPager: ViewPager2, item: Int) {
        if (item == -1) {
            return
        }
        viewPager.setCurrentItem(item, true)
        val bottomNavigationView =
            (viewPager.rootView).findViewById<BottomNavigationView>(R.id.bottom_main)
        var homeItem = bottomNavigationView.menu.findItem(R.id.navigation_home)
        MainHandler.post {
            homeItem.isChecked = true
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["bindTabAndPage"], requireAll = false)
    fun initTabAndPage(viewPager: ViewPager2, initTabAndPage: String) {
        viewPager.setUserInputEnabled(false)
        viewPager.setOffscreenPageLimit(3)
        if (initTabAndPage == "0") {
            viewPager.setAdapter(MainFragment.FragmentPagerAdapter((viewPager.context as FragmentActivity?)!!))
        } else if (initTabAndPage == "1") {
            viewPager.setAdapter(MainFragment.FragmentPagerAdapter2((viewPager.context as FragmentActivity?)!!))
        } else if (initTabAndPage == "2") {
            viewPager.setAdapter(MainFragment.FragmentPagerAdapter3((viewPager.context as FragmentActivity?)!!))
        } else {
            viewPager.setAdapter(MainFragment.FragmentPagerAdapter((viewPager.context as FragmentActivity?)!!))
        }
        val bottomNavigationView =
            (viewPager.rootView).findViewById<BottomNavigationView>(R.id.bottom_main)
        bottomNavigationView.setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener { item: MenuItem? ->
            val itemId = item!!.itemId
            if (itemId == R.id.navigation_home) {
                viewPager.setCurrentItem(0, false)
            } else if (itemId == R.id.navigation_repayment) {
                if (AppConfig.isLogin) {
                    viewPager.setCurrentItem(1, false)
                } else {
                    viewPager.context.startActivity(
                        Intent(
                            viewPager.context,
                            LoginActivity::class.java
                        )
                    )
                    var homeItem = bottomNavigationView.menu.findItem(R.id.navigation_home)
                    MainHandler.post {
                        homeItem.isChecked = true
                    }
                    false
                }
            } else if (itemId == R.id.navigation_mine) {
                if (AppConfig.isLogin) {
                    viewPager.setCurrentItem(2, false)
                } else {
                    viewPager.context.startActivity(
                        Intent(
                            viewPager.context,
                            LoginActivity::class.java
                        )
                    )
                    var homeItem = bottomNavigationView.menu.findItem(R.id.navigation_home)
                    MainHandler.post {
                        homeItem.isChecked = true
                    }
                    false
                }
            }
            true
        })
    }

    @JvmStatic
    @BindingAdapter(value = ["imageFile", "placeHolder"], requireAll = false)
    fun setImageFile(view: AppCompatImageView, file: File, placeHolder: Int) {
        Glide.with(view.context).load(file).placeholder(placeHolder)
            .into(view)
    }

    @JvmStatic
    @BindingAdapter(value = ["imageUrl", "placeHolder"], requireAll = false)
    fun imageUrl(view: ImageView, url: String?, placeHolder: Drawable?) {
        if (url != null && !url.isEmpty() && !url.contains("http")) {
            Glide.with(view.context).load(Const.URL_IMG + url).placeholder(placeHolder)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(view)
        } else {
            Glide.with(view.context).load(url).placeholder(placeHolder)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(view)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["bankNumFormat"], requireAll = false)
    fun bankNumFormat(textView: AppCompatTextView, str: String) {
        if (str.isNotBlank()) {
            textView.text = HtmlCompat.fromHtml(
                str.let {
                    when {
                        it.length <= 5 -> it
                        else -> it.take(2) + "*".repeat(it.length - 5) + it.takeLast(3)
                    }
                }.replace("&", "&amp;")
                    .replace("<", "&lt;")
                    .replace(">", "&gt;")
                    .replace("\n", "<br>"),
                HtmlCompat.FROM_HTML_MODE_LEGACY
            )

        }

    }


    @JvmStatic
    @BindingAdapter(value = ["tagAdapter"], requireAll = false)
    fun tagAdapter(tagFlowLayout: TagFlowLayout, adapter: TagFlowAdapter<*>?) {
        tagFlowLayout.adapter = adapter
    }


    @JvmStatic
    @BindingAdapter(value = ["isDefBank"], requireAll = false)
    fun isDefBank(view: View, hipshot: Boolean) {
        if (view.id == R.id.cl_bank_list_root) {
            if (hipshot) {
                view.setBackgroundResource(R.drawable.rounded_8dp_sytem_background)
            } else {
                view.setBackgroundResource(R.drawable.rounded_8dp_white_background)
            }
        }
        if (view.id == R.id.tv_bank_name || view.id == R.id.tv_bank_num) {
            if (hipshot) {
                (view as AppCompatTextView).setTextColor(ResUtil.getColor(R.color.white))
            } else {
                (view as AppCompatTextView).setTextColor(ResUtil.getColor(R.color.black))
            }
        }
        if (view.id == R.id.iv_isDef || view.id == R.id.tv_isDef) {
            if (hipshot) {
                view.visibility = View.VISIBLE
            } else {
                view.visibility = View.GONE
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["mImageAdapter"], requireAll = false)
    fun setImageAdapter(mRecyclerView: RecyclerView, mAdapter: RecyclerView.Adapter<*>?) {
        val manager = FullyGridLayoutManager(
            mRecyclerView.context,
            5, GridLayoutManager.VERTICAL, false
        )
        mRecyclerView.setLayoutManager(manager)
        val itemAnimator = mRecyclerView.itemAnimator
        if (itemAnimator != null) {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        }
        mRecyclerView.addItemDecoration(
            GridSpacingItemDecoration(
                5, DensityUtil.dip2px(mRecyclerView.context, 8f).toInt(), false
            )
        )
        mRecyclerView.setAdapter(mAdapter)
    }


    @JvmStatic
    @BindingAdapter(value = ["bindCountDownListener"], requireAll = false)
    fun bindCountDownListener(
        countDownTextView: CountDownTextView,
        listener: CountDownTextView.OnCountDownListener?
    ) {
        countDownTextView.setOnCountDownListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["bindCodeCompleteListener"], requireAll = false)
    fun bindCodeCompleteListener(
        codeInputView: CodeInputView,
        listener: CodeInputView.OnCodeCompleteListener?
    ) {
        codeInputView.setOnCodeCompleteListener(listener)
    }


    @JvmStatic
    @BindingAdapter(value = ["loginEnabled"], requireAll = false)
    fun setLoginEnabled(textView: AppCompatButton, text: String) {
        if (text.length >= 4) {
            textView.setBackgroundDrawable(ResUtil.getDrawable(R.drawable.rounded_8dp_blue_background))
            textView.isEnabled = true
        } else {
            textView.setBackgroundDrawable(ResUtil.getDrawable(R.drawable.rounded_8dp_blue_background))
            textView.isEnabled = false
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["verificationCodeState"], requireAll = false)
    fun setVerificationCodeState(view: View, state: Int) {

        val phoneViews = setOf(
            R.id.et_phone_input,
            R.id.tv_phone_num_start,
            R.id.line
        )

        when (state) {
            0 -> {
                view.visibility = if (view.id in phoneViews) View.VISIBLE else View.INVISIBLE
                if (view.id == R.id.code_input_view) {
                    view.visibility = View.INVISIBLE
                    if (view is CodeInputView) {
                        view.clearAll()
                    }
                }
                if (view.id == R.id.tv_register_tip) {
                    view.visibility = View.VISIBLE
                    if (view is AppCompatTextView) {
                        view.text = ResUtil.getString(R.string.not_register_tip)
                    }
                }
            }

            1 -> {
                view.visibility = if (view.id in phoneViews) View.INVISIBLE else View.VISIBLE
                if (view.id == R.id.code_input_view) {
                    view.visibility = View.VISIBLE
                    if (view is CodeInputView && view.isNotEmpty()) {
                        if (view[0] is AppCompatEditText) {
                            view[0].requestFocus()
                        }
                    }
                }
                if (view.id == R.id.tv_count_down) {
                    if (view is CountDownTextView) {
                        view.start()
                    }
                }
                if (view.id == R.id.tv_register_tip) {
                    if (view is AppCompatTextView) {
                        view.text = ResUtil.getString(
                            R.string.verification_code_sent_with_phone,
                            Const.MINUTEMAN,
                            AppConfig.loginPhone
                        )
                    }
                }
            }

            2 -> {
                if (view.id == R.id.et_phone_input) {
                    view.setBackgroundDrawable(ResUtil.getDrawable(R.drawable.rounded_8dp_grey30_red_border_background))
                }
            }

            else -> {
            }
        }

    }


    @JvmStatic
    @BindingAdapter(value = ["editTextError"], requireAll = false)
    fun setEditTextState(textInputEditText: AppCompatEditText, error: String) {
        if (error.isNotEmpty()) {
            textInputEditText.setBackgroundDrawable(ResUtil.getDrawable(R.drawable.rounded_8dp_grey30_red_border_background))
            textInputEditText.error = error
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["formAdapter"], requireAll = false)
    fun setFormAdapter(recyclerView: RecyclerView, adapter: FormGroupAdapter) {
        val formGroup = adapter.formGroup
        recyclerView.adapter = adapter
        recyclerView.layoutManager = FormLayoutManager(recyclerView.context, formGroup)
//        recyclerView.addItemDecoration(
//            FormItemDecoration(
//                recyclerView.context, ContextCompat.getColor(
//                    recyclerView.context,
//                    com.raedev.forms.R.color.form_hint_primary
//                )
//            ).apply {
//                height = 2
//                paddingBottom = 200
//            }
//        )
    }

    @JvmStatic
    @BindingAdapter(value = ["listLayoutManager"], requireAll = false)
    fun setLayoutManager(recyclerView: RecyclerView, numberOfColumns: Int) {
        recyclerView.setLayoutManager(GridLayoutManager(recyclerView.context, numberOfColumns))
    }

    @JvmStatic
    @BindingAdapter(value = ["productCount"], requireAll = false)
    fun productCount(view: View, count: Int) {
        if (view.id == R.id.cl_empty) {
            if (count > 0) {
                view.visibility = View.GONE
            } else {
                view.visibility = View.VISIBLE
            }
        }
        if (view.id == R.id.rv_recommend) {
//            if (count > 1) {
//                view.visibility = View.VISIBLE
//            } else {
//                view.visibility = View.GONE
//            }
        }
        if (view.id == R.id.tv_apply_vay || view.id == R.id.tv_total_loan_amount || view.id == R.id.tv_selected_product) {
            if (count == 0) {
                view.visibility = View.GONE
            } else {
                view.visibility = View.VISIBLE
            }
        }
        if (!AppConfig.isLogin) {
            view.visibility = View.GONE
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["repaymentOrder", "reviewOrder"], requireAll = false)
    fun setOrderView(view: View, repaymentOrder: Int, reviewOrder: Int) {
        if (view.id == R.id.cl_review) {
            if (reviewOrder == 0) {
                view.visibility = View.GONE
            } else {
                view.visibility = View.VISIBLE
            }
        }
        if (view.id == R.id.cl_repayment) {
            if (repaymentOrder == 0) {
                view.visibility = View.GONE
            } else {
                view.visibility = View.VISIBLE
            }
        }

        if (view.id == R.id.sp_order) {
            if (repaymentOrder == 0 || reviewOrder == 0) {
                view.visibility = View.GONE
            } else {
                view.visibility = View.VISIBLE
            }
        }


        when {
            repaymentOrder > 0 && reviewOrder > 0 -> {
                when (view.id) {
                    R.id.tv_repay_view_multi, R.id.tv_review_view_multi -> view.visibility =
                        View.VISIBLE

                    R.id.tv_repay_view_single, R.id.tv_review_view_single -> view.visibility =
                        View.GONE
                }
            }

            (repaymentOrder > 0 && reviewOrder == 0) || (repaymentOrder == 0 && reviewOrder > 0) -> {
                when (view.id) {
                    R.id.tv_repay_view_single, R.id.tv_review_view_single -> view.visibility =
                        View.VISIBLE

                    R.id.tv_repay_view_multi, R.id.tv_review_view_multi -> view.visibility =
                        View.GONE
                }
            }
        }


        if (view.id == R.id.iv_banner) {
            val currentHeight = view.layoutParams.height
            var dynamicHeight = 0f

            dynamicHeight = if (repaymentOrder > 0 && reviewOrder > 0) {
                305f
            } else if ((repaymentOrder > 0 && reviewOrder == 0) || (repaymentOrder == 0 && reviewOrder > 0)) {
                233f
            } else {
                return
            }
            val targetHeight = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dynamicHeight,
                view.context.resources.displayMetrics
            ).toInt()
            ValueAnimator.ofInt(currentHeight, targetHeight).apply {
                duration = 300
                interpolator = AccelerateDecelerateInterpolator()
                addUpdateListener { animator ->
                    val animatedValue = animator.animatedValue as Int
                    view.layoutParams.height = animatedValue
                    view.requestLayout()
                }
                start()
            }

            view.layoutParams.width = ConstraintLayout.LayoutParams.MATCH_PARENT
            (view as AppCompatImageView).setImageResource(R.mipmap.home_top_bg2)
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["formCount"], requireAll = false)
    fun formCount(view: View, count: Int) {
        if (count > 0) {
            view.visibility = View.VISIBLE
        } else {
            view.visibility = View.INVISIBLE
        }

        if (view.id == R.id.tv_total_loan_amount ||
            view.id == R.id.tv_recommend ||
            view.id == R.id.rv_recommend ||
            view.id == R.id.tv_selected_product ||
            view.id == R.id.tv_apply_vay ||
            view.id == R.id.tv_top_tip
        ) {
            if (count > 0) {
                view.visibility = View.INVISIBLE
            } else {
                view.visibility = View.VISIBLE
            }
        }
        if (
            view.id == R.id.tv_avatar ||
            view.id == R.id.tv_app_name ||
            view.id == R.id.iv_security ||
            view.id == R.id.tv_security ||
            view.id == R.id.iv_private ||
            view.id == R.id.tv_private
        ) {
            if (count > 0) {
                view.visibility = View.VISIBLE
            } else {
                view.visibility = View.GONE
            }
        }
        if (view.id == R.id.iv_banner) {
            view.visibility = View.VISIBLE
            val layoutParams = view.layoutParams
            var imageId = if (count > 0) R.mipmap.home_top_bg else R.mipmap.home_top_bg3
            var height = if (count > 0) 338f else 154f
            // 获取当前高度和目标高度
            val currentHeight = view.layoutParams.height
            val targetHeight = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                height,
                view.context.resources.displayMetrics
            ).toInt()
            // 创建高度动画
            ValueAnimator.ofInt(currentHeight, targetHeight).apply {
                duration = 300 // 动画时长 300 毫秒
                interpolator = AccelerateDecelerateInterpolator()  // 平滑插值器
                addUpdateListener { animator ->
                    val animatedValue = animator.animatedValue as Int
                    layoutParams.height = animatedValue
                    view.layoutParams = layoutParams
                    view.requestLayout()  // 请求重绘
                }
                start()
            }
            // 保留原有图片设置逻辑
            layoutParams.width = ConstraintLayout.LayoutParams.MATCH_PARENT
            (view as AppCompatImageView).setImageResource(imageId)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["formProgress"], requireAll = false)
    fun formProgress(view: PercentageSeekBar, type: Int) {
        view.setProgress(type * 25, true)
    }

    @JvmStatic
    @BindingAdapter(value = ["emptyView"], requireAll = false)
    fun emptyView(view: View, size: Int) {
        if (size == 0) {
            view.visibility = View.VISIBLE
        } else {
            view.visibility = View.GONE
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["formType"], requireAll = false)
    fun setFormType(view: View, type: String) {
        if (view.id == R.id.recyclerView) {
            view.visibility = View.VISIBLE
        } else if (view.id == R.id.tv_face_tip || view.id == R.id.tv_face_detail_tip || view.id == R.id.iv_face) {
            view.visibility = if (type == Const.PDS) View.VISIBLE else View.GONE
        } else if (view.id == R.id.id_card_tip || view.id == R.id.iv_card_tip) {
            view.visibility = if (type == Const.SEPTA) View.VISIBLE else View.GONE
        }
        if (view.id == R.id.pg_finish || view.id == R.id.tv_tip) {
            view.visibility = if (type == Const.PDS) View.GONE else View.VISIBLE
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["uploadSuccess", "uploadRes"], requireAll = false)
    fun uploadSuccess(view: AppCompatImageView, isSuccess: Boolean, type: Boolean) {
        view.visibility = if (isSuccess) View.VISIBLE else View.GONE
        if (type) {
            view.setImageResource(R.mipmap.upload_success_icon)
        } else {
            view.setImageResource(R.mipmap.upload_fail_icon)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["ocrState"], requireAll = false)
    fun ocrState(view: View, type: String) {
        // 设置圆角半径（单位：像素）
        val radius = 32f
        view.outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {
                outline.setRoundRect(0, 0, view.width, view.height, radius)
            }
        }
        view.clipToOutline = true
        if (type == "2") {
            if (view is CameraView) view.takePictureSnapshot()
            return
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["liveState"], requireAll = false)
    fun liveState(view: View, type: String) {
        if (type == "4") {
            if (view is CameraView) view.takePictureSnapshot()
            return
        }
        if (type == "3" && view.id == R.id.bt_live) {
            (view as AppCompatButton).text = "Được gửi đi."
        } else if (type == "1" && view.id == R.id.bt_live) {
            (view as AppCompatButton).text = "Thử lại đi"
        } else if (type == "2" && view.id == R.id.bt_live) {
            (view as AppCompatButton).text = "Và bắt đầu nhận ra"
        }
        val typeIds = mapOf(
            "1" to setOf(
                R.id.tv_live_tip,
                R.id.iv_live_enter,
                R.id.iv_live_fail1,
                R.id.iv_live_fail2,
                R.id.iv_live_fail3
            ),
            "2" to setOf(R.id.camera, R.id.iv_live_take),
            "3" to setOf(
                R.id.tv_certification_success,
                R.id.iv_certification_success,
                R.id.tv_to_submit
            )
        )
        typeIds.forEach { (targetType, ids) ->
            if (view.id in ids) {
                view.visibility = if (type == targetType) View.VISIBLE else View.GONE
                return@forEach  // 找到匹配项后提前退出
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["isRepaymentTypeSelected"], requireAll = false)
    fun isRepaymentTypeSelected(view: View, isSelected: Boolean) {
        if (view.id == R.id.cl_repayment_type_root) {
            if (isSelected) {
                view.setBackgroundResource(R.drawable.rounded_8dp_blue2_background)
            } else {
                view.setBackgroundResource(R.drawable.rounded_8dp_grey_background3)

            }
        }
        if (view.id == R.id.iv_repayment_type_selected) {
            var imageView = view as AppCompatImageView
            if (isSelected) {
                imageView.setImageResource(R.mipmap.selected_icon)
            } else {
                imageView.setImageResource(R.mipmap.selected_icon_def)
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["isSelected"], requireAll = false)
    fun setSelected(view: View, isSelected: Boolean) {
        if (view.id == R.id.cl_bank_list_def) {
            if (isSelected) {
                view.setBackgroundResource(R.drawable.rounded_8dp_orange_border_background)
            } else {
                view.setBackgroundColor(ResUtil.getColor(R.color.transparent))
            }
        }

        if (view.id == R.id.cl_recommend_root) {
            if (isSelected) {
                view.setBackgroundResource(R.drawable.rounded_8dp_orange_border_background)
            } else {
                view.setBackgroundResource(R.drawable.rounded_8dp_white_background)
            }
        }

        if (view.id == R.id.iv_select) {
            var imageView = view as ImageView
            if (isSelected) {
                imageView.setImageResource(R.mipmap.select_icon)
            } else {
                imageView.setImageResource(R.mipmap.un_select_icon)
            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["loanCalculateQuantity"], requireAll = false)
    fun setLoanCalculateQuantity(
        textView: AppCompatTextView,
        data: ArrayList<ProductInfoApi.ThoroughBean>
    ) {

        val text = when {
            data.isEmpty() -> "Sản phẩm vay mượn (đã chọn 0 Sản phẩm)"
            else -> {
                val selectedItems = data.filter { it.isSelected }
                val quantity = selectedItems.count()
                "Sản phẩm vay mượn (đã chọn $quantity Sản phẩm)"
            }
        }
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf("("),
            text.length,
            ContextCompat.getColor(textView.context, R.color.grey_630)
        )
        // 设置文本
        textView.text = spannableString
    }


    @JvmStatic
    @BindingAdapter(value = ["calculateQuantity"], requireAll = false)
    fun setCalculateQuantity(
        textView: AppCompatTextView,
        data: ArrayList<ProductInfoApi.ThoroughBean>
    ) {
        val text = when {
            data.isEmpty() -> "Đã chọn 0 sản phẩm"
            else -> {
                val quantity = data.count()
                "Đã chọn $quantity sản phẩm"
            }
        }
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf(data.count().toString()),
            text.indexOf("s"),
            ContextCompat.getColor(textView.context, R.color.orange_700)
        )
        // 设置文本
        textView.text = spannableString
    }

    @JvmStatic
    @BindingAdapter(value = ["selected"], requireAll = false)
    fun setBorrowingAmount(view: AppCompatImageView, selected: Boolean) {
        if (selected) {
            view.setImageResource(R.mipmap.select_icon)
        } else {
            view.setImageResource(R.mipmap.un_select_icon)

        }
    }

    @JvmStatic
    @BindingAdapter(value = ["doubleFormat"], requireAll = false)
    fun doubleFormat(textView: AppCompatTextView, data: Double) {
        textView.text = SpannableUtils.getDoubleFormat(data)
    }

    class ViewHolder internal constructor(view: View) {
        var tvCustomTitle: TextView = view.findViewById<TextView?>(R.id.tv_custom_title)
        var tvCustomValue: TextView = view.findViewById<TextView?>(R.id.tv_custom_value)
    }


    @JvmStatic
    @BindingAdapter(value = ["addView"], requireAll = false)
    fun addView(
        detailsContentLL: LinearLayoutCompat,
        list: ArrayList<HandlingChargeApi.QualitativeBean>
    ) {
        val inflater = LayoutInflater.from(detailsContentLL.context)
        val layoutRes = R.layout.layout_customization
        for (qualitativeBean in list) {
            val view = inflater.inflate(layoutRes, detailsContentLL, false) // 正确传递父容器
            val holder = ViewHolder(view)
            holder.tvCustomTitle.text =
                if (!TextUtils.isEmpty(qualitativeBean.cpcu)) qualitativeBean.cpcu else ""
            holder.tvCustomValue.text =
                if (!TextUtils.isEmpty(qualitativeBean.superempirical)) qualitativeBean.superempirical else ""
            detailsContentLL.addView(view)
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["borrowingAmount"], requireAll = false)
    fun setBorrowingAmount(textView: AppCompatTextView, data: Double) {
        if (data.isNaN()) {
            return
        }
        textView.text = Const.CURRENCY_SYMBOL + SpannableUtils.getDoubleFormat(data)
    }

    @JvmStatic
    @BindingAdapter(value = ["repaymentPeriod"], requireAll = false)
    fun repaymentPeriod(textView: AppCompatTextView, data: Int) {
        var date = Utils.getFutureDateCompat(data)
        textView.text = date
    }

    @JvmStatic
    @BindingAdapter(value = ["accountCollection"], requireAll = false)
    fun setAccountCollection(imageView: AppCompatImageView, data: Int) {
        val resourceMap = mapOf(
            Pair(R.id.iv_bank_card, mapOf(0 to R.mipmap.select_icon, 1 to R.mipmap.un_select_icon)),
            Pair(R.id.iv_wallet, mapOf(1 to R.mipmap.select_icon, 0 to R.mipmap.un_select_icon))
        )
        resourceMap[imageView.id]?.get(data)?.let { resourceId ->
            imageView.setImageResource(resourceId)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["uploadText", "uploadText2"], requireAll = false)
    fun uploadText(textView: AppCompatTextView, data: String, data2: String) {
        if (data.isEmpty()) {
            return
        }
        val text = data + data2
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf(data2),
            text.length,
            ContextCompat.getColor(textView.context, R.color.orange_700)
        )

        textView.text = spannableString
    }


    @JvmStatic
    @BindingAdapter(value = ["repaymentPeriod"], requireAll = false)
    fun setRepaymentPeriod(textView: AppCompatTextView, data: String) {
        if (data.isEmpty()) {
            return
        }
        val text = "Thời gian (ngày):${data}"
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf(data),
            text.length,
            ContextCompat.getColor(textView.context, R.color.black)
        )

        textView.text = spannableString
    }


    @JvmStatic
    @BindingAdapter(value = ["calculationAmount"], requireAll = false)
    fun setCalculationAmount(
        textView: AppCompatTextView,
        data: ArrayList<ProductInfoApi.ThoroughBean>
    ) {
        val text = when {
            data.isEmpty() -> "Tổng số tiền vay (₫):0,00"
            else -> {
                val amount = data.sumOf { it.nuciform }
                val amountFormat = SpannableUtils.getDoubleFormat(amount)
                "Tổng số tiền vay (₫):${amountFormat}"
            }
        }
        // 使用工具类设置金额部分的颜色为橘色
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf("("),
            text.length,
            ContextCompat.getColor(textView.context, R.color.orange_700)
        )
        // 设置文本
        textView.text = spannableString
    }

    @JvmStatic
    @BindingAdapter(value = ["fullText", "clickableText"], requireAll = false)
    fun setSpannable(textView: AppCompatTextView, fullText: String, clickableText: String) {
        val fullText = fullText
        val clickableText = clickableText
        // 检查子字符串是否存在
        val startIndex = fullText.indexOf(clickableText)
        if (startIndex < 0) {
            textView.text = fullText
            return
        }
        val endIndex = startIndex + clickableText.length
        val spannableString = SpannableString(fullText)
        textView.setTextColor(ResUtil.getColor(R.color.grey_610))
        textView.movementMethod = LinkMovementMethod.getInstance();
        spannableString.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    // 处理点击事件
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ResUtil.getColor(R.color.blue_800)
                    ds.isUnderlineText = true
                }
            },
            startIndex,
            endIndex,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        textView.text = spannableString
        textView.movementMethod = LinkMovementMethod.getInstance()
        textView.highlightColor = Color.TRANSPARENT
    }

    @JvmStatic
    @BindingAdapter(value = ["titleBarText"], requireAll = false)
    fun setTitleBarText(textView: TitleBar, text: String?) {
        textView.setTitle(text)
    }


    //    @BindingAdapter(value = ["refreshListener"], requireAll = false)
//    fun refreshListener(view: SmartRefreshLayout, listener: OnRefreshListener?) {
//        view.setOnRefreshListener(listener)
//    }
//
//    @BindingAdapter(value = ["loadListener"], requireAll = false)
//    fun loadListener(view: SmartRefreshLayout, listener: OnLoadMoreListener?) {
//        view.setOnLoadMoreListener(listener)
//    }
    @JvmStatic
    @BindingAdapter(value = ["bindScrollViewListener"], requireAll = false)
    fun bindScrollViewListener(
        nestedScrollView: NestedScrollView,
        listener: NestedScrollView.OnScrollChangeListener?
    ) {
        nestedScrollView.setOnScrollChangeListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["bindTitleBarListener"], requireAll = false)
    fun listenTitleBar(titleBar: TitleBar, listener: OnTitleBarListener?) {
        titleBar.setOnTitleBarListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["titleBarTitle"], requireAll = false)
    fun titleBarTitle(titleBar: TitleBar, title: String?) {
        titleBar.setTitle(title)
    }


    @JvmStatic
    @BindingAdapter(value = ["bindRefreshListener"], requireAll = false)
    fun bindRefreshListener(refreshLayout: SwipeRefreshLayout, listener: OnRefreshListener?) {
        refreshLayout.setOnRefreshListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["refreshState"], requireAll = false)
    fun refreshState(refreshLayout: SwipeRefreshLayout, isRefresh: Boolean) {
        refreshLayout.isRefreshing = isRefresh
    }

    @JvmStatic
    @BindingAdapter(value = ["refreshEnabled"], requireAll = false)
    fun refreshEnabled(refreshLayout: SwipeRefreshLayout, isEnabled: Boolean) {
        refreshLayout.isEnabled = isEnabled
    }


    @JvmStatic
    @BindingAdapter(value = ["cameraListener"], requireAll = false)
    fun cameraListener(cameraView: CameraView, listener: CameraListener) {
        cameraView.addCameraListener(listener)
    }


    @JvmStatic
    @BindingAdapter(value = ["bindOnKeyListener"], requireAll = false)
    fun listenOnKey(editText: EditText, listener: View.OnKeyListener?) {
        editText.setOnKeyListener(listener)
    }


    @JvmStatic
    @BindingAdapter(value = ["bindEmptyListener"], requireAll = false)
    fun emptyListener(view: EmptyView, listener: EmptyView.OnEmptyListener?) {
        view.setOnEmptyListener(listener)
    }

    @JvmStatic
    @BindingAdapter(value = ["emptyLayout"], requireAll = false)
    fun emptyLayout(layout: EmptyView, isEmpty: Boolean) {
        if (isEmpty) {
            layout.visibility = View.VISIBLE
        } else {
            layout.visibility = View.GONE
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["unfinishedFormCount"], requireAll = false)
    fun unfinishedFormCount(layout: View, count: Int) {
        if (count == 0) {
            layout.visibility = View.VISIBLE
        } else {
            layout.visibility = View.GONE
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["stateLayout"], requireAll = false)
    fun stateLayout(layout: StateLayout, type: Int) {
        if (type == 0) {
            layout.showContent()
        } else if (type == 1) {
            layout.showEmpty()
        } else if (type == 2) {
            layout.showError()
        } else if (type == 3) {
            layout.showLoading()
        }
    }

}
